<template>
  <div class="operation-report">
    <!-- 页面标题 -->
    <div class="report-header">
      <h2 class="page-title">操作统计报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-button type="success" icon="Download" @click="handleExport">
          导出报表
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon primary">
            <el-icon><Document /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.totalOperations || 0 }}</div>
            <div class="card-label">总操作次数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon success">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.successOperations || 0 }}</div>
            <div class="card-label">成功操作</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon danger">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.failedOperations || 0 }}</div>
            <div class="card-label">失败操作</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon warning">
            <el-icon><User /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.activeUsers || 0 }}</div>
            <div class="card-label">活跃用户</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 操作趋势图 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>操作趋势分析</span>
              <el-radio-group v-model="trendType" size="small" @change="handleTrendTypeChange">
                <el-radio-button label="day">按天</el-radio-button>
                <el-radio-button label="hour">按小时</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="operationTrendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 操作类型分布 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>操作类型分布</span>
            </div>
          </template>
          <div ref="operationTypeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细分析 -->
    <el-row :gutter="20" class="detail-row">
      <!-- 模块操作分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>模块操作分布</span>
            </div>
          </template>
          <div ref="moduleChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 用户操作排行 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>用户操作排行</span>
            </div>
          </template>
          <div class="user-ranking">
            <div v-for="(item, index) in userRanking" :key="index" class="ranking-item">
              <div class="ranking-number">{{ index + 1 }}</div>
              <div class="ranking-user">{{ item.userName }}</div>
              <div class="ranking-count">{{ item.count }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 操作时间分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>操作时间分布</span>
            </div>
          </template>
          <div ref="timeDistributionChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>操作详细记录</span>
          <div class="table-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索用户/操作"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
            <el-select v-model="businessTypeFilter" placeholder="操作类型" clearable style="width: 120px" @change="handleSearch">
              <el-option label="新增" value="1" />
              <el-option label="修改" value="2" />
              <el-option label="删除" value="3" />
              <el-option label="授权" value="4" />
              <el-option label="导出" value="5" />
            </el-select>
            <el-select v-model="statusFilter" placeholder="状态" clearable style="width: 100px" @change="handleSearch">
              <el-option label="成功" value="0" />
              <el-option label="失败" value="1" />
            </el-select>
          </div>
        </div>
      </template>
      
      <el-table v-loading="tableLoading" :data="operationData" stripe>
        <el-table-column prop="title" label="操作模块" width="120" />
        <el-table-column prop="businessType" label="操作类型" width="80">
          <template #default="{ row }">
            <dict-tag :options="businessTypeOptions" :value="row.businessType" />
          </template>
        </el-table-column>
        <el-table-column prop="method" label="请求方法" width="80" />
        <el-table-column prop="operName" label="操作人员" width="100" />
        <el-table-column prop="operIp" label="操作IP" width="120" />
        <el-table-column prop="operLocation" label="操作地点" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operTime" label="操作时间" width="160" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getOperationData"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getOperationReport, exportOperationReport } from '@/api/report/operation'
import DictTag from '@/components/DictTag/index.vue'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const dateRange = ref<string[]>([])
const trendType = ref('day')
const searchText = ref('')
const businessTypeFilter = ref('')
const statusFilter = ref('')
const tableLoading = ref(false)
const total = ref(0)

// 概览数据
const overview = reactive({
  totalOperations: 0,
  successOperations: 0,
  failedOperations: 0,
  activeUsers: 0,
})

// 用户排行数据
const userRanking = ref<any[]>([])

// 操作数据
const operationData = ref<any[]>([])

// 字典选项
const businessTypeOptions = ref([
  { label: '其他', value: '0' },
  { label: '新增', value: '1' },
  { label: '修改', value: '2' },
  { label: '删除', value: '3' },
  { label: '授权', value: '4' },
  { label: '导出', value: '5' },
])

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  startDate: '',
  endDate: '',
  title: '',
  operName: '',
  businessType: '',
  status: '',
})

// 图表引用
const operationTrendChartRef = ref()
const operationTypeChartRef = ref()
const moduleChartRef = ref()
const timeDistributionChartRef = ref()

// 图表实例
let operationTrendChart: echarts.ECharts
let operationTypeChart: echarts.ECharts
let moduleChart: echarts.ECharts
let timeDistributionChart: echarts.ECharts

// 获取报表数据
const getReportData = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
      trendType: trendType.value,
    }
    
    // 模拟数据
    const mockData = {
      overview: {
        totalOperations: 2856,
        successOperations: 2679,
        failedOperations: 177,
        activeUsers: 125,
      },
      trendData: generateMockTrendData(),
      typeData: [
        { name: '新增', value: 856 },
        { name: '修改', value: 624 },
        { name: '删除', value: 324 },
        { name: '导出', value: 280 },
        { name: '授权', value: 156 },
        { name: '其他', value: 616 },
      ],
      moduleData: [
        { name: '用户管理', value: 856 },
        { name: '角色管理', value: 524 },
        { name: '菜单管理', value: 324 },
        { name: '部门管理', value: 280 },
        { name: '字典管理', value: 156 },
        { name: '其他', value: 716 },
      ],
      timeData: generateMockTimeData(),
    }
    
    // 更新概览数据
    Object.assign(overview, mockData.overview)
    
    // 渲染图表
    nextTick(() => {
      renderOperationTrendChart(mockData.trendData)
      renderOperationTypeChart(mockData.typeData)
      renderModuleChart(mockData.moduleData)
      renderTimeDistributionChart(mockData.timeData)
    })
  } catch (error) {
    console.error('获取操作报表数据失败:', error)
    ElMessage.error('获取操作报表数据失败')
  }
}

// 获取操作数据表格
const getOperationData = async () => {
  tableLoading.value = true
  try {
    // 模拟数据
    operationData.value = generateMockOperationData()
    total.value = 50
  } catch (error) {
    console.error('获取操作数据失败:', error)
  } finally {
    tableLoading.value = false
  }
}

// 渲染操作趋势图表
const renderOperationTrendChart = (data: any[]) => {
  if (!operationTrendChartRef.value) return
  
  if (!operationTrendChart) {
    operationTrendChart = echarts.init(operationTrendChartRef.value)
  }
  
  const times = data.map(item => item.time)
  const successCounts = data.map(item => item.success)
  const failCounts = data.map(item => item.fail)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['成功操作', '失败操作']
    },
    xAxis: {
      type: 'category',
      data: times
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成功操作',
        type: 'bar',
        stack: 'total',
        data: successCounts,
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '失败操作',
        type: 'bar',
        stack: 'total',
        data: failCounts,
        itemStyle: { color: '#F56C6C' }
      }
    ]
  }
  
  operationTrendChart.setOption(option)
}

// 渲染操作类型分布图表
const renderOperationTypeChart = (data: any[]) => {
  if (!operationTypeChartRef.value) return
  
  if (!operationTypeChart) {
    operationTypeChart = echarts.init(operationTypeChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  operationTypeChart.setOption(option)
}

// 渲染模块分布图表
const renderModuleChart = (data: any[]) => {
  if (!moduleChartRef.value) return
  
  if (!moduleChart) {
    moduleChart = echarts.init(moduleChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        data: data,
        label: {
          fontSize: 12
        }
      }
    ]
  }
  
  moduleChart.setOption(option)
}

// 渲染时间分布图表
const renderTimeDistributionChart = (data: any[]) => {
  if (!timeDistributionChartRef.value) return
  
  if (!timeDistributionChart) {
    timeDistributionChart = echarts.init(timeDistributionChartRef.value)
  }
  
  const hours = data.map(item => item.hour + ':00')
  const counts = data.map(item => item.count)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: hours
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: counts,
        type: 'line',
        smooth: true,
        itemStyle: { color: '#E6A23C' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230, 162, 60, 0.2)' },
            { offset: 1, color: 'rgba(230, 162, 60, 0)' }
          ])
        }
      }
    ]
  }
  
  timeDistributionChart.setOption(option)
}

// 生成模拟趋势数据
const generateMockTrendData = () => {
  const data = []
  const today = new Date()
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today.getTime() - i * 24 * 60 * 60 * 1000)
    data.push({
      time: date.toISOString().split('T')[0],
      success: Math.floor(Math.random() * 400) + 200,
      fail: Math.floor(Math.random() * 50) + 10,
    })
  }
  
  return data
}

// 生成模拟时间分布数据
const generateMockTimeData = () => {
  const data = []
  
  for (let i = 0; i < 24; i++) {
    data.push({
      hour: i,
      count: Math.floor(Math.random() * 100) + 10,
    })
  }
  
  return data
}

// 生成模拟操作数据
const generateMockOperationData = () => {
  const mockData = []
  const titles = ['用户管理', '角色管理', '菜单管理', '部门管理', '字典管理']
  const methods = ['GET', 'POST', 'PUT', 'DELETE']
  const users = ['admin', 'manager', 'user1', 'user2']
  
  for (let i = 0; i < 10; i++) {
    mockData.push({
      title: titles[i % titles.length],
      businessType: String((i % 5) + 1),
      method: methods[i % methods.length],
      operName: users[i % users.length],
      operIp: `192.168.1.${100 + i}`,
      operLocation: '本地',
      status: Math.random() > 0.1 ? 0 : 1,
      operTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString(),
    })
  }
  
  return mockData
}

// 日期范围变化
const handleDateChange = () => {
  refreshData()
}

// 趋势类型变化
const handleTrendTypeChange = () => {
  getReportData()
}

// 搜索
const handleSearch = () => {
  queryForm.title = searchText.value
  queryForm.businessType = businessTypeFilter.value
  queryForm.status = statusFilter.value
  queryForm.pageNum = 1
  getOperationData()
}

// 刷新数据
const refreshData = () => {
  getReportData()
  getOperationData()
}

// 导出报表
const handleExport = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
    }
    
    ElMessage.success('报表导出成功')
  } catch (error) {
    ElMessage.error('报表导出失败')
  }
}

// 初始化用户排行数据
const initUserRanking = () => {
  userRanking.value = [
    { userName: 'admin', count: 856 },
    { userName: 'manager', count: 624 },
    { userName: 'user1', count: 324 },
    { userName: 'user2', count: 256 },
    { userName: 'user3', count: 186 },
  ]
}

// 初始化
onMounted(() => {
  // 设置默认日期范围（最近7天）
  const today = new Date()
  const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  dateRange.value = [
    lastWeek.toISOString().split('T')[0],
    today.toISOString().split('T')[0]
  ]
  
  refreshData()
  initUserRanking()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    operationTrendChart?.resize()
    operationTypeChart?.resize()
    moduleChart?.resize()
    timeDistributionChart?.resize()
  })
})
</script>

<style lang="scss" scoped>
.operation-report {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.overview-row,
.charts-row,
.detail-row {
  margin-bottom: 20px;
}

.overview-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    .el-icon {
      font-size: 24px;
      color: white;
    }
    
    &.primary {
      background: linear-gradient(135deg, #409EFF, #6BB7FF);
    }
    
    &.success {
      background: linear-gradient(135deg, #67C23A, #95D475);
    }
    
    &.warning {
      background: linear-gradient(135deg, #E6A23C, #F0C674);
    }
    
    &.danger {
      background: linear-gradient(135deg, #F56C6C, #FF8A95);
    }
  }
  
  .card-content {
    .card-number {
      font-size: 28px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 5px;
    }
    
    .card-label {
      font-size: 14px;
      color: #606266;
    }
  }
}

.chart-card,
.detail-card,
.table-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  
  .table-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.chart-container {
  width: 100%;
  height: 300px;
}

.chart-container-small {
  width: 100%;
  height: 250px;
}

.user-ranking {
  .ranking-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .ranking-number {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background: #409EFF;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 600;
    }
    
    .ranking-user {
      flex: 1;
      margin-left: 12px;
      font-weight: 500;
      color: #303133;
    }
    
    .ranking-count {
      color: #E6A23C;
      font-weight: 600;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .operation-report {
    padding: 10px;
  }
  
  .report-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
    
    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }
  
  .overview-card {
    padding: 15px;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container-small {
    height: 200px;
  }
}
</style>

